#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
执行缓存表模型 (ExecutionCache)
"""

from sqlalchemy import Column, String, Integer, Float, DateTime, Index
from sqlalchemy.sql import func
from typing import Optional

from .BaseModel import BaseModel

class ExecutionCache(BaseModel):
    """执行缓存表模型"""
    __tablename__ = 'execution_cache'
    
    execution_date = Column(String(10), primary_key=True)
    strategy_type = Column(String(50), primary_key=True)
    results_count = Column(Integer, default=0)
    execution_time = Column(Float, default=0.0)
    created_at = Column(DateTime, default=func.current_timestamp())
    updated_at = Column(DateTime, default=func.current_timestamp(), onupdate=func.current_timestamp())
    
    # 索引
    __table_args__ = (
        Index('idx_cache_execution_date', 'execution_date'),
        Index('idx_cache_strategy_type', 'strategy_type'),
    )
    
    @classmethod
    def get_session(cls):
        """获取数据库会话"""
        return cls._db_manager.get_stock_selection_session()
    
    @classmethod
    def _get_existing_record(cls, session, data):
        """获取现有记录"""
        return session.query(cls).filter(
            cls.execution_date == data['execution_date'],
            cls.strategy_type == data['strategy_type']
        ).first()
    
    @classmethod
    def _update_existing_record(cls, existing, data):
        """更新现有记录"""
        existing.results_count = data.get('results_count', existing.results_count)
        existing.execution_time = data.get('execution_time', existing.execution_time)
        existing.updated_at = func.current_timestamp()
    
    @classmethod
    def _to_dict(cls, result):
        """将结果转换为字典"""
        return {
            'execution_date': result.execution_date,
            'strategy_type': result.strategy_type,
            'results_count': result.results_count,
            'execution_time': result.execution_time,
            'created_at': result.created_at,
            'updated_at': result.updated_at
        }
    
    @classmethod
    def save_cache(cls, execution_date: str, strategy_type: str, 
                   results_count: int, execution_time: float) -> bool:
        """保存执行缓存"""
        return cls.save_batch([{
            'execution_date': execution_date,
            'strategy_type': strategy_type,
            'results_count': results_count,
            'execution_time': execution_time
        }])
    
    @classmethod
    def get_cache(cls, execution_date: str, strategy_type: str) -> Optional[dict]:
        """获取执行缓存"""
        if not cls._db_manager:
            raise ValueError("数据库管理器未设置，请先调用 set_db_manager()")
        
        try:
            session = cls.get_session()
            
            cache = session.query(cls).filter(
                cls.execution_date == execution_date,
                cls.strategy_type == strategy_type
            ).first()
            session.close()
            
            if cache:
                return {
                    'results_count': cache.results_count,
                    'execution_time': cache.execution_time,
                    'created_at': cache.created_at,
                    'updated_at': cache.updated_at
                }
            return None
        except Exception as e:
            # 获取执行缓存失败: {str(e)}
            session.close()
            return None
